const express = require("express")
const md5 = require("md5")
const route = express.Router()
//引入token函数
const {tokenEncode,tokenDecode} = require("../utils/JWT")
//引入数据库集合
const adminModel = require("../db/model/adminModel")
route.post("/login", async (req, res) => {
    const {
        adminName,
        password
    } = req.body
    const findResult = await adminModel.findOne({
        adminName,
        password:md5(password+"123")
    })
    try {
        if (!findResult) {
            return res.send({
                "code": 10001,
                "msg": "用户名或密码错误",
                "data": null
            })
        }
         //登录成功把用户的状态码改为1
     await  adminModel.updateOne({adminName},{
        $set:{
            state:1
        }
    })
         //生成token
      const token =   tokenEncode(adminName)
        res.send({
            "code": 10000,
            "msg": "ok",
            "data": {
                token: token
            }
        })
      
    } catch (e) {
        console.log("登录异常" + e.message);
        res.send({
            "code": 10002,
            "msg": "登录异常" + e.message,
            "data": null
        })
    }
})

module.exports = route